const timestamp = Date.now();
const pkgJson = require("./package.json");
import { visualizer } from 'rollup-plugin-visualizer'
import viteCompression from 'vite-plugin-compression'
import type { PluginOption } from 'vite'

const version = pkgJson.version;

export default defineNuxtConfig({
    devtools: { enabled: false },
    app: {
        head: {
            meta: [
                {
                    name: "description",
                    content:
                        "华锐云空间包括汽车、冶金、电力、消防、化工、畜牧、文旅等海量3D展厅及课件模板，搭配AI数字人就能搭建专属企业3D线上展厅。电话：13611042909",
                },
                {
                    name: "keywords",
                    content: "3D展厅，线上编辑器，AI数字人，3D微课，元宇宙制作",
                },
                {
                    name: "viewport",
                    content:
                        "width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no viewport-fit=cover",
                },
                process.env.NODE_ENV === "production"
                    ? {
                        "http-equiv": "Cache-Control",
                        content: "no-cache, no-store, must-revalidate",
                    }
                    : {},
                process.env.NODE_ENV === "production"
                    ? {
                        "http-equiv": "Pragma",
                        content: "no-cache",
                    }
                    : {},
                process.env.NODE_ENV === "production"
                    ? {
                        "http-equiv": "Expires",
                        content: "0",
                    }
                    : {},
            ],
            script: [
                {
                    src: "/js/jweixin-1.6.0.js",
                    tagPosition: "head",
                },
                {
                    src: "/js/ie.js",
                    tagPosition: "head",
                },
                {
                    src: "/js/jsmpeg.min.js",
                    tagPosition: "head",
                },
                process.env.NODE_ENV === "development"
                    ? {
                        src: "/js/vconsole.min.js",
                        tagPosition: "head",
                    }
                    : {},
                process.env.NODE_ENV === "production"
                    ? {
                        type: "text/javascript",
                        tagPosition: "head",
                        innerHTML: `
                            var _hmt = _hmt || [];
                            (function() {
                                var hm = document.createElement("script");
                                hm.src = "https://hm.baidu.com/hm.js?a8e99580444afd63f16a87a7adfc7b7e";
                                var s = document.getElementsByTagName("script")[0];
                                s.parentNode.insertBefore(hm, s);
                            })();
                        `,
                    }
                    : {},
                {
                    type: "text/javascript",
                    tagPosition: "head",
                    innerHTML: `var _v_ = '${version}';var _t_ = ${new Date().getTime()}`,
                },
            ],
            title: "免费试用_3D展厅搭建_AI数字人_元宇宙公司_课件编辑器——北京华锐云空间",
        },
        buildAssetsDir: "/static/",
    },

    build: {
        analyze: {
            analyzerMode: "static",
        },
    },
    vite: {
        css: {
            devSourcemap: false, // 关闭开发源映射
            preprocessorOptions: {
                scss: {
                    additionalData: `
                        @use "@/assets/css/element-variables.scss" as element;
                    `,
                },
            },
        },
        build: {
            sourcemap: false,
            cssCodeSplit: false, // 强制合并 CSS
            rollupOptions: {
                output: {
                    entryFileNames: `static/[name]_[hash:8]_.${version}.js`,
                    chunkFileNames: `static/[name]_[hash:8]_.${version}.js`,
                    assetFileNames: `static/[name]_[hash:8]_.${version}.[ext]`,
                    manualChunks(id) {
                        // if (id.includes('node_modules')) {
                        //     const match = id.match(/node_modules\/(.*?)(\/|$)/)
                        //     const packageName = match ? match[1] : ''
                        //     // 核心库独立打包
                        //     const coreLibs = ['lodash', 'qrcode', 'axios', 'crypto-js']
                        //     if (coreLibs.includes(packageName)) {
                        //         return 'vendor-core'
                        //     }
                        //     if (['element-plus', 'varlet', 'siwper'].includes(packageName)) {
                        //         return 'vendor-ui'
                        //     }
                        //     return 'vendor-ext' // 其他依赖
                        // }
                        if (id.includes("element-plus")) return "element-plus";
                        if (id.includes("varlet")) return "varlet";
                        if (id.includes("lodash-es")) return "lodash";
                        if (id.includes("qrcode")) return "qrcode";
                        if (id.includes("axios")) return "axios";
                        if (id.includes("crypto-js")) return "crypto-js";
                        if (id.includes("siwper")) return "siwper";
                        if (
                            /\/(views|pages)\/(.+?)\/(index|P|M).(vue|js|scss)/.test(
                                id
                            )
                        ) {
                            return `${RegExp.$1}-${RegExp.$2.replace(
                                "/",
                                "-"
                            )}`;
                        }
                    },
                },
            },
        },
        optimizeDeps: {
            include: [
                "vue",
                "swiper",
                "element-plus",
                // "varlet",
                // "loadsh-es",
                "qrcode",
                "axios",
                "crypto-js",
            ],
        },
        plugins: [
            // 构建分析
            visualizer({
                open: true,
                filename: '.nuxt/stats.html'
            }) as PluginOption,
            viteCompression({
                algorithm: 'gzip',
                threshold: 10240 // 大于 10KB 的文件压缩
            })
        ]
    },

    devServer: {
        port: 3003,
        host: "0.0.0.0",
    },

    experimental: {
        inlineSSRStyles: false,
    },

    runtimeConfig: {
        timestamp,
        public: {
            baseUrl: process.env.NUXT_PUBLIC_BASE_URL,
        },
    },

    components: {
        dirs: [
            {
                path: "~/layouts/components",
                prefix: "Layout",
            },
            {
                path: "~/dialog",
                prefix: "Dialog",
            },
            {
                path: "~/views",
                prefix: "Views",
            },
            "~/components",
        ],
    },

    postcss: {
        plugins: {
            autoPrefixer: {},
            "postcss-px-to-viewport-8-plugin": {
                unitToConvert: "px", // 要转化的单位
                viewportWidth: 375, // UI设计稿的宽度
                unitPrecision: 3, // 转换后的精度，即小数点位数
                propList: ["*", "!min-width"], // 指定转换的css属性的单位，*代表全部css属性的单位都进行转换
                viewportUnit: "vw", // 指定需要转换成的视窗单位，默认vw
                fontViewportUnit: "vw", // 指定字体需要转换成的视窗单位，默认vw
                selectorBlackList: ["embed-chat-container"], // 指定不转换为视窗单位的类名，
                minPixelValue: 1, // 默认值1，小于或等于1px则不进行转换
                mediaQuery: true, // 是否在媒体查询的css代码中也进行转换，默认false
                replace: true, // 是否转换后直接更换属性值
                exclude: [
                    /node_modules/,
                    /P(.+)?\.vue/,
                    /assets/,
                    /P\.scss/,
                    /error\.vue/,
                ],
                landscape: false, // 是否处理横屏情况
            },
        },
    },

    css: ["normalize.css", "~/assets/css/reset.css"],
    modules: [
        "@pinia/nuxt",
        "@element-plus/nuxt",
        "@varlet/nuxt",
        "nuxt-vite-legacy",
        "dayjs-nuxt",
        "@nuxt/image",
    ],
    dayjs: {
        locales: ["en", "ja"],
        plugins: ["relativeTime", "utc", "timezone"],
        defaultLocale: "en",
    },
    elementPlus: {
        importStyle: "scss",
    },
    varlet: {},
    image: {
        inject: true,
        quality: "80",
    },
    legacy: {
        targets: ["chrome 49"],
        // renderLegacyChunks: false,
        additionalLegacyPolyfills: [
            "mdn-polyfills/Element.prototype.getAttributeNames",
        ],
        modernPolyfills: [
            "es.global-this",
            "es/object",
            "es/array",
            "es/promise",
            "es/string",
        ],
    },
    hooks: {
        'build:manifest'(manifest) {
            for (const item of Object.values(manifest)) {
                item.dynamicImports = []
                item.prefetch = false
                item.preload = false
            }
        },
    },
});
